package com.zzg.controller;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;


/**
 *绘制验证码
 */
@WebServlet("/code.do")
public class CodeServlet extends HttpServlet {
	private static final int WIDTH = 100;
	private static final int HEIGHT = 50;
	private static final int FONT_SIZE = 20;
	private static final String CHARS="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	private static final Color[] COLORS = {Color.BLUE,Color.PINK,Color.YELLOW,Color.RED,Color.ORANGE};
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//创建内存图片
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_ARGB);
		//获得绘图对象
		Graphics g = image.getGraphics();
		//设置颜色
		g.setColor(Color.DARK_GRAY);
		//设置字体
		g.setFont(new Font("宋体",Font.PLAIN,FONT_SIZE));
		//填充矩形
		g.fillRect(0, 0, WIDTH, HEIGHT);
		g.setColor(Color.BLUE);
		
		Random random = new Random();
		StringBuilder str = new StringBuilder();
		for(int i = 0;i < 4;i++){
			int index = random.nextInt(CHARS.length());
			char c  = CHARS.charAt(index);
			str.append(c);
			g.setColor(COLORS[random.nextInt(COLORS.length)]);
			
			g.drawString(String.valueOf(c),15+i*FONT_SIZE, 30);
			g.setColor(COLORS[random.nextInt(COLORS.length)]);
			g.drawLine(random.nextInt(WIDTH),random.nextInt(HEIGHT), random.nextInt(WIDTH),random.nextInt(HEIGHT));
		}
		
		//通过Servlet的输出流，将图片发送给浏览器
		req.getSession().setAttribute("code", str);
		ImageIO.write(image, "PNG",resp.getOutputStream());
	}
}
